import userStore from "@/store/modules/user";
import {getUserInfoByTokenApi,getUserResourceByTokenApi} from "@/api/system/auth/authApi";
import router from '@/router/route';
import type { RouteRecordRaw } from 'vue-router'
import modules from "@/components/componentRegister";
const filterAsyncRouter = (userRouterList) => {
    return userRouterList.filter(route => {
        if (route.component) {
            route.component = modules[route.component]
        }
        if (route.children && route.children.length) {
            route.children = filterAsyncRouter(route.children)
        }
        return true
    })
}
/**
 * 全局前置路由守卫，每一次路由跳转前都进入这个 beforeEach 函数
 * 登录页面放行，如果不是登录页面，先判断token是否存在，不存在就跳转登录，存在的话判断有没有获取过用户信息，没获取的话获取后再跳转
 */
router.beforeEach(async (to, from, next) => {
    const useUserStore = userStore()
    if(to.path === '/login'){
        next()
    }else{
        const token = useUserStore.getUserToken
        if(!token){
            next(`/login?redirect=${to.path}`);
        }else{
            const userInfo = useUserStore.getUserInfo
            if(!userInfo.username){
                // 请求用户信息
                await getUserInfoByTokenApi().then((res:any)=>{
                    useUserStore.SET_USER_INFO(res.result)
                })
                // 获取菜单\路由\按钮
                await getUserResourceByTokenApi().then((res:any)=>{
                    let oldRouterListStr = JSON.stringify(res.result.routerList)
                    let oldRouterList = JSON.parse(oldRouterListStr)
                    useUserStore.SET_ROUTER_LIST(oldRouterList)

                    useUserStore.SET_BTN_LIST(res.result.btnList)
                    useUserStore.SET_MENU_LIST(res.result.menuList)
                    // 用户拥有的按钮和菜单权限x
                    let routers = filterAsyncRouter(res.result.routerList)
                    routers.forEach(route => {
                        router.addRoute(route)
                    })
                    next({...to, replace: true})//确保路由添加成功
                })
            }else{
                // 如果当前路由只有三个默认路由则添加缓存的路由信息
                if(router.getRoutes().length === 3 && useUserStore.getUserRouterList.length > 0){
                    let storeRouterStr = JSON.stringify(useUserStore.getUserRouterList)
                    let storeRouters = JSON.parse(storeRouterStr)
                    let routers:RouteRecordRaw[] = filterAsyncRouter(storeRouters)
                    routers.forEach(route => {
                        router.addRoute(route)
                    })
                    next({...to, replace: true})//确保路由添加成功
                }else{
                    // 没有匹配的路由
                    if(to.matched.length === 0){
                        if(from.name){
                            next({name:from.name})
                        }else{
                            next('/404')
                        }
                    }else{
                        next()
                    }
                }
            }
        }
    }

});

export default router
